package com.dz51.core.validate.validator.handler;  

import javax.servlet.http.HttpServletRequest;

import com.dz51.core.validate.annotation.ParamValidater;
import com.dz51.core.validate.annotation.ValidateItem;
import com.dz51.core.validate.util.ValidateResultBulider;
import com.dz51.core.validate.validator.strategy.ValidateModel;
import com.dz51.core.validate.vo.ValidateResult;
  
public class DefaultValidateHandler implements ValidateHandler{

    private ValidateExecuter validateExecuter = new ValidateExecuter();
    
    @Override
    public ValidateResult handleValidate(HttpServletRequest request, ParamValidater[] rules) {
        //如果参数有问题，直接返回成功
        if(request == null || rules == null || rules.length == 0){
            return ValidateResultBulider.createSuccessResult(request);
        }
        //循环判断每个参数
        for (ParamValidater paramValidater : rules) {
            if(paramValidater == null){
                continue;
            }
            if(paramValidater.validators() == null || paramValidater.validators().length == 0){
                break;
            }
            
            //对trim的处理
            if(paramValidater.trim()){
                String param = request.getParameter(paramValidater.name());
                if(param != null){
                    param = param.trim();
                    request.setAttribute(paramValidater.name(), param);
                }
                param = request.getParameter(paramValidater.name());
                System.out.println("===================过滤后" + param);
            }
            
            for (ValidateItem validateItem : paramValidater.validators()) {
                ValidateModel model = validateItem.validateType().getValidateModel();
                ValidateResult validateResult = validateExecuter.validate(request, paramValidater, model);
                if(validateResult == null){
                    continue;
                }
                if(validateResult.getRequest() != null){
                    request = validateResult.getRequest();
                }
                if(validateResult.isSuccess()){
                    continue;
                }else{
                    return ValidateResultBulider.createFailResult(request, validateItem.errorMsg(), validateItem.code()); //返回错误信息
                }
            }
        }
        return ValidateResultBulider.createSuccessResult(request);
    }


    
}
